<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Package\Message\Message;
use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use App\Http\Requests\Auth\RegisterRequest;
use Illuminate\Foundation\Auth\RegistersUsers;

/**
 * 用户注册逻辑
 *
 * Date: 20/03/2018
 * @author George
 * @package App\Http\Controllers\Auth
 */
class RegisterController extends Controller
{
    use RegistersUsers;

    protected $userRepository;

	/**
	 * RegisterController constructor.
	 * @param UserRepository $userRepository
	 */
	public function __construct(UserRepository $userRepository)
	{
		$this->userRepository = $userRepository;
	}

	/**
	 * 用户注册
	 *
	 * Date: 11/04/2018
	 * @author George
	 * @param RegisterRequest $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \App\Exceptions\GeneralException
	 */
	public function register(RegisterRequest $request)
	{
		$message = new Message();
		$result = $message->verification($request->mobile, $request->code);

		if ($result) {
			$attributes = $request->only(['mobile', 'password']);
			$user = $this->userRepository->create($attributes);

			return success([
				'access_token' => auth('user')->tokenById($user->id),
				'token_type' => 'Bearer',
				'expires_in' => config('jwt.ttl') * 60
			]);
		}

		return failed('您输入的验证码有误');
    }

	/**
	 * 验证手机号码是否可以注册
	 *
	 * Date: 25/03/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function registerable(Request $request)
	{
		$this->validate($request, [
			'mobile' => ['required', 'regex:/^(1[3|4|5|6|7|8|9])\d{9}$/', 'unique:users,mobile']
		],[
			'mobile.required' => '请输入手机号码',
			'mobile.regex' => '您输入的手机号码有误',
			'mobile.unique' => '您输入的手机号码已存在'
		]);

		return message('可以注册');
    }
}
